package com.gy.paidao.person;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

import com.gy.paidao.BaseActivity;
import com.gy.paidao.MainActivity;
import com.gy.paidao.MyApplication;
import com.gy.paidao.R;
import com.gy.paidao.bean.BaseBean;
import com.gy.paidao.parse.BaseParse;
import com.gy.paidao.person.bean.LoginBean;
import com.gy.paidao.util.AnimUtil;
import com.gy.paidao.util.LogUtil;
import com.gy.paidao.util.SPHelper;
import com.gy.paidao.util.Urls;
import com.jky.struct2.http.core.AjaxParams;
import com.jky.struct2.http.entityhandle.HttpResult;

import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * 作者：gy on 16/2/17
 * 说明：登录
 */
public class LoginActivity extends BaseActivity{

    private EditText etName,etPassword;
    private TextView tvLogin,tvForger,tvRegister;
    private String strName,strPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setViews();
    }

    @Override
    protected void initVariable() {

    }

    @Override
    protected void setTitleViews() {

    }

    @Override
    protected void setViews() {
        etName = (EditText) findViewById(R.id.activity_login_et_name);
        etPassword = (EditText) findViewById(R.id.activity_login_et_password);
        tvLogin = (TextView) findViewById(R.id.activity_login_tv_login);
        tvRegister = (TextView) findViewById(R.id.activity_login_tv_register);
        tvForger = (TextView) findViewById(R.id.activity_login_tv_forget);

        tvLogin.setOnClickListener(this);
        tvRegister.setOnClickListener(this);
        tvForger.setOnClickListener(this);
    }

    @Override
    protected void doClickAction(int viewId) {
        super.doClickAction(viewId);
        switch (viewId){
            case R.id.activity_login_tv_login:
                strName = etName.getText().toString().trim();
                strPassword = etPassword.getText().toString().trim();
                if(TextUtils.isEmpty(strName) || TextUtils.isEmpty(strPassword)){
                    showToast(R.string.activity_login_input_error);
                } else {
                    requestLogin();
                }
                break;
            case R.id.activity_login_tv_forget:
                intent = new Intent(this,ForgetActivity.class);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(this);
                break;
            case R.id.activity_login_tv_register:
                intent = new Intent(this,RegisterActivity.class);
                startActivityForResult(intent,101);
                AnimUtil.pushLeftInAndOut(this);
                break;
        }
    }

    private void requestLogin(){
        showLoading();
        params = new AjaxParams();
        params.put("account",strName+"");
        params.put("password",strPassword+"");
        httpRequest.post(Urls.url_login, params, callBack, 0);
    }

    @Override
    protected void handlerBean(int requestCode, BaseBean baseBean) {
        super.handlerBean(requestCode, baseBean);
        if(baseBean.success){
            cookieHandler.sendEmptyMessageDelayed(0, 0);
            String data = String.valueOf(baseBean.data);
            LoginBean bean = gson.fromJson(data,LoginBean.class);
            MyApplication.loginBean = bean;
            MyApplication.USERID = bean.id;
            intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            AnimUtil.pushLeftInAndOut(this);
            LoginActivity.this.finish();
        } else {
            if("0010006".equals(baseBean.errCode)){
                String data = String.valueOf(baseBean.data);
                try {
                    JSONObject obj = new JSONObject(data);
                    int userId = obj.optInt("userId");
                    intent = new Intent(this,RegisterEmailActivity.class);
                    intent.putExtra("userId",userId);
                    intent.putExtra("email",strName);
                    startActivity(intent);
                    AnimUtil.pushLeftInAndOut(this);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
            if(!TextUtils.isEmpty(baseBean.errMsg)){
                showToast(baseBean.errMsg);
            }
        }
    }

    private Handler cookieHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            DefaultHttpClient httpClient;
            httpClient = (DefaultHttpClient) httpRequest.getHttpClient();
            CookieStore mCookieStore = httpClient.getCookieStore();
            List<Cookie> cookies = mCookieStore.getCookies();
            for (int i = 0; i < cookies.size(); i++) {
                LogUtil.e(cookies.get(i).getName() + "  " + cookies.get(i).getValue());
                if("userLoginID".equals(cookies.get(i).getName())){
                    SPHelper.getInstance(LoginActivity.this).setStringData("userLoginID",cookies.get(i).getValue());
                }
            }
        };
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 101){
            this.finish();
        }
    }
}
